//
//  SCPayManager.m
//  SCPaymentDemo
//
//  Created by Tang_ShaoCheng on 15/11/5.
//  Copyright © 2015年 Tang_ShaoCheng. All rights reserved.
//

#import "SCPayManager.h"

#define WX_APP_ID       @"wx15091e3bf78ded98"
#define WX_APP_SECRET   @"f19e9a33df38819e5cdc47dfb693a9ee"
#define WX_MCH_ID       @"1282773101"
#define WX_PARTNER_ID   @"ye6tgr8Vj9dict35dDrewM109aid8c7i"
#define WX_NOTIFY_URL   @"http://notify.test.wx.cn-cic.com/PaymentGate/WechatPay/"
//http://doc.open.alipay.com/doc2/detail?spm=0.0.0.0.ahvF6G&treeId=59&articleId=103678&docType=1
#define ALI_APP_ID       @"2015110200664177"
#define ALI_PARTNER_ID   @"2088711009416445"
#define ALI_SELLER_ACCOUNT   @"hr@cardapp.com.hk"
#define ALI_NOTIFY_URL   @"http://notify.test.wx.cn-cic.com/PaymentGate/Alipay/"

@implementation SCPayManager

-(id)init;
{
    self = [super init];
    if (self)
    {
        [WXApi registerApp:WX_APP_ID];
    }
    return self;
}

#pragma mark 微信支付

- (void)wechatPay;
{
    NSString *order_Name = _order_Name;
    NSString *order_No = _order_No;
    int order_Price = _order_Price;//分
    NSString *order_Type = @"APP";
    NSString *ip = @"192.168.1.1";
    srand((unsigned)time(0));
    NSString *noncestr = [NSString stringWithFormat:@"%d",rand()];
    NSMutableDictionary *packageParams = [NSMutableDictionary dictionary];
    [packageParams setObject: WX_APP_ID  forKey:@"appid"];  //开放平台appid
    [packageParams setObject: WX_MCH_ID  forKey:@"mch_id"]; //商户号
    [packageParams setObject: @"iOS"  forKey:@"device_info"];   //支付设备号或门店号
    [packageParams setObject: noncestr     forKey:@"nonce_str"];    //随机串
    [packageParams setObject: order_Type    forKey:@"trade_type"];  //支付类型，固定为APP
    [packageParams setObject: order_Name    forKey:@"body"];    //订单描述，展示给用户
    [packageParams setObject: WX_NOTIFY_URL  forKey:@"notify_url"]; //支付结果异步通知
    [packageParams setObject: order_No      forKey:@"out_trade_no"];    //商户订单号
    [packageParams setObject: ip      forKey:@"spbill_create_ip"];  //发器支付的机器ip
    [packageParams setObject: [NSString stringWithFormat:@"%d",_order_Price]   forKey:@"total_fee"];    //订单金额，单位为分

    NSString *sign = [self createMd5Sign:packageParams];

    //生成xml的package
    NSMutableString *reqPars=[NSMutableString string];
    [reqPars appendString:@"<xml>\n"];
    for (NSString *key in packageParams)
    {
        [reqPars appendFormat:@"<%@>%@</%@>",key,[packageParams objectForKey:key],key];
    }
    [reqPars appendFormat:@"<sign>%@</sign>\n</xml>",sign];
    NSData *res = [WXUtil httpSend:@"https://api.mch.weixin.qq.com/pay/unifiedorder" method:@"POST" data:reqPars];
    XMLHelper *xml  = [[XMLHelper alloc] init];
    //开始解析
    [xml startParse:res];
    NSMutableDictionary *resParams = [xml getDict];
    NSString *return_code = [resParams objectForKey:@"return_code"];
    NSString *result_code = [resParams objectForKey:@"result_code"];
    if ([return_code isEqualToString:@"SUCCESS"]&&[result_code isEqualToString:@"SUCCESS"])
    {
        NSDate *datenow = [NSDate date];
        NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
        UInt32 timeStamp =[timeSp intValue];
        NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
        [signParams setObject: WX_APP_ID  forKey:@"appid"];  //开放平台appid
        [signParams setObject: WX_MCH_ID  forKey:@"partnerid"]; //商户号
        [signParams setObject: @"Sign=WXPay" forKey:@"package"];
        [signParams setObject: resParams[@"nonce_str"] forKey:@"noncestr"];
        [signParams setObject: [NSString stringWithFormat:@"%u",timeStamp] forKey:@"timestamp"];
        [signParams setObject: resParams[@"prepay_id"] forKey:@"prepayid"];
        NSString *new_Sign = [self createMd5Sign:signParams];
        
        PayReq *request = [[PayReq alloc]init];
        request.partnerId = WX_MCH_ID;
        request.prepayId= resParams[@"prepay_id"];
        request.package = @"Sign=WXPay";
        request.nonceStr= resParams[@"nonce_str"];
        request.timeStamp= timeStamp;
        request.sign= new_Sign;
        [WXApi sendReq:request];
    }
}

-(NSString*)createMd5Sign:(NSMutableDictionary*)dict
{
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [dict allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (   ![[dict objectForKey:categoryId] isEqualToString:@""]
            && ![categoryId isEqualToString:@"sign"]
            && ![categoryId isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [dict objectForKey:categoryId]];
        }
        
    }
    //添加key字段
    [contentString appendFormat:@"key=%@",WX_PARTNER_ID];
    //得到MD5 sign签名
    NSString *md5Sign =[WXUtil md5:contentString];
    return md5Sign;
}

#pragma mark 支付宝支付

- (void)aliPay;
{
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = [[NSBundle mainBundle]objectForInfoDictionaryKey:@"CFBundleName"];
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [self description];
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(@"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMZvn9IMvazlqfiZ+rSV972pAimSgIe4NZO9SKiInOPPdVW5uevkaWgfVZFq8EiQtvyK8qX8zj8MIsQmW4X6Pab6pRD0AA6OmtRglRt9IuN+4rRro6t7VGSeA5624Uj254n1CAF5JAwcnLegRYIdg9R3/CIsS77Yn7jv19q42qTXAgMBAAECgYACQ8vjLdoMWyKxf7Bo1z1YoNExgEaPRf72jLaDleuUfg2syM3ib1z0n0buvfW4Hk64Wy2hz1zbQ1wyOO3afZyughCJyQVNAaRRW1nvZW37yRbT6m1ViBYfC8RdfwrjZg9fEIo/aQsLYlUeoGt4vhKk8NxrMg0cBbm2+9MhUY0LwQJBAOVRyj0T95BBWK2FlZM9qrLV2kVyNnFWiugqPhZ3gOEcP6Y32GAmXDmU/75bO90IctSw/DXz1GKUdlCRgyVluVkCQQDdhfrjCuH3DSmsdUGujo9cRKL12ds6Blx8jaalwe4XlYPV5LZYfjmu1htKm9g0XvhlOVUICSySMrfT8RLkyVmvAkEApyz+M5K32slYvX9yMJo3NBKlAhWmTO/bai9JfhV2tiVi3Wk+67FrcGsIGhzmwldjZ1zzMN3lykwTCN9b7UqAWQJAXz7F+mypb2GXc3EPBpCBDzjroC1FVxN5HIyDBG33guhkQMkPpcjP4F5qaY/MS+gxgMQ/zS60nT91TokuiHQSPQJAeejR1g93PRTIM9Jzg+9Ib4FNzF3Dx5WeDz5x1pqZJ5y9LNfXSiR+oPJoyrh5KRX2tgnbHt+d+mas9zwNdjiBiQ==");
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"ali_payOrderResult = %@",resultDic);
            
            if ([_myDelegate respondsToSelector:@selector(didFinishPay:wechatPay:)])
            {
                [_myDelegate didFinishPay:YES wechatPay:NO];
            }
        }];
    }
}

- (NSString *)description {
    NSMutableString * discription = [NSMutableString string];
    if (ALI_PARTNER_ID) {
        [discription appendFormat:@"partner=\"%@\"", ALI_PARTNER_ID];
    }
    if (ALI_SELLER_ACCOUNT) {
        [discription appendFormat:@"&seller_id=\"%@\"", ALI_SELLER_ACCOUNT];
    }
    if (_order_No) {
        [discription appendFormat:@"&out_trade_no=\"%@\"", _order_No];
    }
    if (_order_Name) {
        [discription appendFormat:@"&subject=\"%@\"", _order_Name];
    }
    if (_order_Description) {
        [discription appendFormat:@"&body=\"%@\"", _order_Description];
    }
    if (_order_Price) {
        [discription appendFormat:@"&total_fee=\"%.2f\"", _order_Price/100.0];
    }
    if (ALI_NOTIFY_URL) {
        [discription appendFormat:@"&notify_url=\"%@\"", ALI_NOTIFY_URL];
    }
    if (1) {
        [discription appendFormat:@"&service=\"%@\"",@"mobile.securitypay.pay"];//mobile.securitypay.pay
    }
    if (1) {
        [discription appendFormat:@"&payment_type=\"%@\"",@"1"];//1
    }
    if (1) {
        [discription appendFormat:@"&_input_charset=\"%@\"",@"utf-8"];//utf-8
    }
    if (1) {
        [discription appendFormat:@"&it_b_pay=\"%@\"",@"30m"];//30m
    }
    if (1) {
        [discription appendFormat:@"&show_url=\"%@\"",@"m.alipay.com"];//m.alipay.com
    }
    if (ALI_APP_ID) {
        [discription appendFormat:@"&app_id=\"%@\"",ALI_APP_ID];
    }
    return discription;
}

#pragma mark 回调

-(void)onResp:(BaseResp*)resp;
{
    if ([resp isKindOfClass:[PayResp class]])
    {
        switch (resp.errCode)
        {
            case WXSuccess:
            {
                NSLog(@"微信支付成功");
                if ([_myDelegate respondsToSelector:@selector(didFinishPay:wechatPay:)])
                {
                    [_myDelegate didFinishPay:YES wechatPay:YES];
                }
            }
            default:
            {
                NSLog(@"微信支付失败");
                if ([_myDelegate respondsToSelector:@selector(didFinishPay:wechatPay:)])
                {
                    [_myDelegate didFinishPay:NO wechatPay:YES];
                }
                break;
            }
        }
    }
}

@end
